﻿#include "newuser.h"
#include "ui_newuser.h"
#include "cdatabaseinterface.h"
#include "userdataformate.h"
#include <QDir>
#include <QSettings>
#include <QMessageBox>
#include "currentuserdata.h"
#include "customintvalidator.h"
newUser::newUser(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::newUser),
    m_deleteUser(nullptr),
    m_confirUser(nullptr)

{
    ui->setupUi(this);
    //设置搜索框自动补全
    m_completer = new QCompleter();
    m_completer->setFilterMode(Qt::MatchStartsWith);
    m_completer->setCompletionMode(QCompleter::PopupCompletion);
    m_completer->setMaxVisibleItems(7);
    m_completer->setModel(&stringListModel);
    ui->search_lineEdit->setCompleter(m_completer);
    ui->search_lineEdit->setPlaceholderText(tr("姓名或者ID"));
    initUserTableWidget();
    updateUserTableWidget();
    this->setWindowFlags(Qt::Dialog|Qt::FramelessWindowHint);
    connect(ui->search_lineEdit,SIGNAL(editingFinished()),this,SLOT(editComplete()));
    connect(ui->search_lineEdit,&QLineEdit::textChanged,[this](const QString text){
        if(text == "")
        {
            updateUserTableWidget();
        }
    });

    m_confirUser = new ConfirmUser();
    m_deleteUser = new DeleteUser();

    ui->ID_lineEdit->setReadOnly(true);

    setInputLimit();

    ui->save_pushButton->setVisible(false);
}

newUser::~newUser()
{
    if(m_deleteUser)
        delete m_deleteUser;
    if(m_confirUser)
        delete m_confirUser;
    if(m_completer)
        delete m_completer;
    delete ui;
}

void newUser::setInputLimit()
{
    //年龄
    CustomIntValidator *ageIntValidator = new CustomIntValidator(1, 100, this);
    ageIntValidator->setRange(1, 150);
    ui->age_lineEdit->setValidator(ageIntValidator);
    //身高
    CustomIntValidator *heightIntValidator = new CustomIntValidator(1, 100, this);
    heightIntValidator->setRange(0,250);
    ui->height_lineEdit->setValidator(heightIntValidator);
    //体重
    CustomIntValidator *weightIntValidator = new CustomIntValidator(1, 100, this);
    weightIntValidator->setRange(0,350);
    ui->weight_lineEdit->setValidator(weightIntValidator);
    //电话
    QRegExp reg("[0-9]+$");
    QRegExpValidator *pValidator = new QRegExpValidator(this);
    pValidator->setRegExp(reg);
    ui->phone_lineEdit->setMaxLength(11);
    ui->phone_lineEdit->setValidator(pValidator);
    //姓名
    ui->name_lineEdit->setMaxLength(8);
}

void newUser::on_newUser_pushButton_clicked()
{
    ui->mask_label->setVisible(false);
    ui->save_pushButton->setVisible(true);
    clearUserData();
    //自动生成ID
    int ID(100000);
    //先查询数据库查找出最大的ID
    QString query(QString("select * from PatientMsg  order by ID DESC"));
    CDatabaseInterface *dataBase = CDatabaseInterface::getInstance();
    if(dataBase->exec(query))
    {
        int size = dataBase->getValuesSize();
        if(size > 0)
        {
            QVariantMap varMap =dataBase->getValues(0,1).at(0);
            ST_PatientMsg st_patient = variantMapToPatientMsg(varMap);
            ID = st_patient.ID+1;
        }
    }
    else
        qDebug()<<dataBase->getLastError();
    ui->ID_lineEdit->setText(QString::number(ID));

}


void newUser::on_delete_pushButton_clicked()
{
    m_deleteUser->show();
    m_deleteUser->exec();
    if(m_deleteUser->isDeletedUser())
    {
        if(!CDatabaseInterface::getInstance()->deleteRowTable("PatientMsg","ID",QString::number(m_currentUserId)))
            qDebug()<<"delete user failed"<<CDatabaseInterface::getInstance()->getLastError();
        updateUserTableWidget();
    }
    else
        return;

}
//保存按钮槽函数
void newUser::on_save_pushButton_clicked()
{
    QRegExp exp("[0-9\\.-]+$");
    QValidator *Validator = new QRegExpValidator(exp);

    ST_PatientMsg st_PatientMsg;
    st_PatientMsg.ID=ui->ID_lineEdit->text().toInt();
    st_PatientMsg.userName = ui->name_lineEdit->text();
    st_PatientMsg.age = ui->age_lineEdit->text().toInt();
    ui->age_lineEdit->setValidator(Validator);

    st_PatientMsg.sex = ui->sex_Cbx->currentIndex();

    st_PatientMsg.height = ui->height_lineEdit->text().toInt();
    ui->height_lineEdit->setValidator(new QIntValidator(0,300,this));
    st_PatientMsg.weight = ui->weight_lineEdit->text().toInt();
    ui->weight_lineEdit->setValidator(new QIntValidator(0,300,this));
    st_PatientMsg.userPhone = ui->phone_lineEdit->text();
    ui->phone_lineEdit->setValidator(new QIntValidator(0,1000000000000,this));
    st_PatientMsg.remarkMessage = ui->remark_textEdit->toPlainText();

    //新建用户的添加，先将数据保存到内存中
    QString tableName("PatientMsg");
    QVariantMap vMap = patientMsgToVariantMap(st_PatientMsg);

    //删除所有空格
    if(st_PatientMsg.userName.remove(QRegExp("\\s")).isEmpty())
    {
        QMessageBox::information(NULL,tr("提示"),tr("用户名不能为空"));
        return;
    }

    if(!CDatabaseInterface::getInstance()->insertRowTable(tableName,vMap))
    {
        QString str = CDatabaseInterface::getInstance()->getLastError();
    }
    else
    {
        emit signalUpdateUserTable();
        QMessageBox::information(NULL,tr("提示"),tr("添加成功"));
        updateUserTableWidget();
    }


    if(!CDatabaseInterface::getInstance()->updateRowTable(tableName,"ID",vMap))
    {
        QString str = CDatabaseInterface::getInstance()->getLastError();
    }
    else
    {
        emit signalUpdateUserTable();
        QMessageBox::information(NULL,tr("提示"),tr("更新成功"));
        updateUserTableWidget();
    }
    ui->mask_label->setVisible(true);
}


void newUser::on_search_pushButton_clicked()

{
    //清理界面
    ui->user_tableWidget->clearContents();
    QString msg = ui->search_lineEdit->text();
    QString query(QString("select * from PatientMsg where userName = '%1' or ID = '%2'").arg(msg).arg(msg));
    QList<QVariantMap> valueMapList;
    if(CDatabaseInterface::getInstance()->exec(query))
    {
        valueMapList = CDatabaseInterface::getInstance()->getValues(0,8);
    }
    if(0 == valueMapList.count())
    {
        qDebug()<<"未找到合适数据";
    }
    fillUserTable(valueMapList);
}

void newUser::clearUserData()
{
    ui->name_lineEdit->clear();
    ui->phone_lineEdit->clear();
    ui->age_lineEdit->clear();
    ui->weight_lineEdit->clear();
    ui->height_lineEdit->clear();
    ui->remark_textEdit->clear();
}

void newUser::on_modify_pushButton_clicked()
{
    ui->mask_label->setVisible(false);
    ui->save_pushButton->setVisible(true);
    //根据ID查找用户
    int ID = m_currentUserId;
    QString queryStr(QString("select * from PatientMsg  where ID = '%1'").arg(ID));
    ST_PatientMsg st_PatientMsg;
    if(CDatabaseInterface::getInstance()->exec(queryStr))
    {
        if(CDatabaseInterface::getInstance()->getValuesSize() > 0)
        {
            QList<QVariantMap> valueMapList;
            valueMapList = CDatabaseInterface::getInstance()->getValues(0,1);
            st_PatientMsg = variantMapToPatientMsg(valueMapList.at(0));

            ui->name_lineEdit->setText(st_PatientMsg.userName);
            ui->phone_lineEdit->setText(st_PatientMsg.userPhone);
            ui->sex_Cbx->setCurrentIndex(st_PatientMsg.sex);
            ui->age_lineEdit->setText(QString::number(st_PatientMsg.age));
            ui->weight_lineEdit->setText(QString::number(st_PatientMsg.weight));
            ui->ID_lineEdit->setText(QString::number(st_PatientMsg.ID));
            ui->height_lineEdit->setText(QString::number(st_PatientMsg.height));
            ui->remark_textEdit->setText(st_PatientMsg.remarkMessage);

        }
        else
        {
            qDebug()<<"未查询到符合条件的数据";
        }
    }

}


//初始化用户列表
void newUser::initUserTableWidget()
{

    //设置表格的列数
    ui->user_tableWidget->setColumnCount(5);
    //设置表格的行数
    ui->user_tableWidget->setRowCount(100);

    ui->user_tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    //设置行高
    QHeaderView *verticalHeader = ui->user_tableWidget->verticalHeader();
    QHeaderView *horizontalHeader = ui->user_tableWidget->horizontalHeader();   
    verticalHeader->setSectionResizeMode(QHeaderView::Fixed);
    verticalHeader->setDefaultSectionSize(68);
    ui->user_tableWidget->verticalHeader()->setDefaultAlignment(Qt::AlignHCenter);
    ui->user_tableWidget->setShowGrid(false);
    //设置列宽
    ui->user_tableWidget->setColumnWidth(0,150);
    ui->user_tableWidget->setColumnWidth(1,125);
    ui->user_tableWidget->setColumnWidth(2,125);
    ui->user_tableWidget->setColumnWidth(3,226);
    ui->user_tableWidget->setColumnWidth(4,226);
    //设置隔行变色
    ui->user_tableWidget->setAlternatingRowColors("true");
    //隐藏列表头
    ui->user_tableWidget->verticalHeader()->setVisible(false);
    //隐藏行表头
    ui->user_tableWidget->horizontalHeader()->setVisible(false);

    ui->user_tableWidget->setFont(QFont("黑体",12));
    //设置表格所有单元格不可编辑
    ui->user_tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //设置单行选中
    ui->user_tableWidget->setSelectionBehavior(QTableWidget::SelectRows);
    ui->user_tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);

    connect(ui->user_tableWidget,&QTableWidget::cellClicked,[this](int row,int column){
        Q_UNUSED(column)
        //根据行列获取用户ID
        if(row >= m_currentRows)
            return;
        m_currentUserId = ui->user_tableWidget->item(row,4)->data(Qt::DisplayRole).toUInt();
//        on_modify_pushButton_clicked();
        fillUserData(m_currentUserId);
        emit signalCheckUserChanged(m_currentUserId);

    });
}

//更新用户列表
void newUser::updateUserTableWidget()
{
    QString queryStr(QString("select * from PatientMsg order by ID DESC"));

    if(CDatabaseInterface::getInstance()->exec(queryStr))
    {
        int tempNum = CDatabaseInterface::getInstance()->getValuesSize();
        int fillTableNum = tempNum < 100 ? tempNum : 100;
        m_currentRows = fillTableNum;
        if(fillTableNum > 0)
        {
            QList<QVariantMap> valueMapList;
            valueMapList = CDatabaseInterface::getInstance()->getValues(0,fillTableNum);
            fillUserTable(valueMapList);
        }
        else
        {
            ui->user_tableWidget->clearContents();
            qDebug()<<"updateUserTableWidget()未查询到符合条件的数据";
        }
    }
    else
        qDebug()<<CDatabaseInterface::getInstance()->getLastError();

    qDebug()<<"更新用户列表";
}


//填充Usertable
void newUser::fillUserTable(const QList<QVariantMap> &ListMap)
{

    ui->user_tableWidget->clearContents();
    wordList.clear();
    for(int row = 0;row < ListMap.size();++row)
    {
        ST_PatientMsg st_PatientMsg = variantMapToPatientMsg(ListMap.at(row));
        //更新自动补全表
        wordList.append(st_PatientMsg.userName);
        wordList.append(QString::number(st_PatientMsg.ID));
        stringListModel.setStringList(wordList);

        //第0列 名字
        QTableWidgetItem *nameItem = new QTableWidgetItem(st_PatientMsg.userName);
        //        nameItem->setFlags(nameItem->flags() & (~Qt::ItemIsEditable));  //设置单个单元格不可编辑
        ui->user_tableWidget->setItem(row, 0, nameItem);
        //第1列 性别
        QString sexStr;
        if(0 == st_PatientMsg.sex)
            sexStr = tr("男");
        else if(1 == st_PatientMsg.sex)
            sexStr = tr("女");
        QTableWidgetItem *sexItem = new QTableWidgetItem(sexStr);
        //        nameItem->setFlags(nameItem->flags() & (~Qt::ItemIsEditable));  //设置单个单元格不可编辑
        ui->user_tableWidget->setItem(row, 1, sexItem);
        //第2列 年龄
        QTableWidgetItem *ageItem = new QTableWidgetItem(QString::number(st_PatientMsg.age));
        ui->user_tableWidget->setItem(row, 2, ageItem);
        //第3列 电话
        QTableWidgetItem *phoneNumberItem = new QTableWidgetItem(st_PatientMsg.userPhone);
        ui->user_tableWidget->setItem(row, 3, phoneNumberItem);

        //第4列 ID
        QTableWidgetItem *IdItem = new QTableWidgetItem(QString::number(st_PatientMsg.ID));
        ui->user_tableWidget->setItem(row, 4, IdItem);

        ui->user_tableWidget->item(row,0)->setTextAlignment(Qt::AlignCenter);
        ui->user_tableWidget->item(row,1)->setTextAlignment(Qt::AlignCenter);
        ui->user_tableWidget->item(row,2)->setTextAlignment(Qt::AlignCenter);
        ui->user_tableWidget->item(row,3)->setTextAlignment(Qt::AlignCenter);
        ui->user_tableWidget->item(row,4)->setTextAlignment(Qt::AlignCenter);
    }
}

void newUser::fillUserData(int ID)
{

    QString queryStr(QString("select * from PatientMsg  where ID = '%1'").arg(ID));
    ST_PatientMsg st_PatientMsg;
    if(CDatabaseInterface::getInstance()->exec(queryStr))
    {
        if(CDatabaseInterface::getInstance()->getValuesSize() > 0)
        {
            QList<QVariantMap> valueMapList;
            valueMapList = CDatabaseInterface::getInstance()->getValues(0,1);
            st_PatientMsg = variantMapToPatientMsg(valueMapList.at(0));

            ui->name_lineEdit->setText(st_PatientMsg.userName);
            ui->phone_lineEdit->setText(st_PatientMsg.userPhone);
            ui->sex_Cbx->setCurrentIndex(st_PatientMsg.sex);
            ui->age_lineEdit->setText(QString::number(st_PatientMsg.age));
            ui->weight_lineEdit->setText(QString::number(st_PatientMsg.weight));
            ui->ID_lineEdit->setText(QString::number(st_PatientMsg.ID));
            ui->height_lineEdit->setText(QString::number(st_PatientMsg.height));
            ui->remark_textEdit->setText(st_PatientMsg.remarkMessage);

        }
        else
        {
            qDebug()<<"未查询到符合条件的数据";
        }
    }
}


void newUser::on_selectUser_pushButton_clicked()
{

    QString queryStr(QString("select * from PatientMsg where ID = '%1'").arg(m_currentUserId));

    if(CDatabaseInterface::getInstance()->exec(queryStr))
    {
        if(CDatabaseInterface::getInstance()->getValuesSize() > 0)
        {
            QVariantMap userMap = CDatabaseInterface::getInstance()->getValues(0,1).at(0);
            ST_PatientMsg st_patientMsg = variantMapToPatientMsg(userMap);

            m_confirUser->setUserMsg(st_patientMsg);
            m_confirUser->show();
            m_confirUser->exec();
            //设置当前用户
            if(m_confirUser->isSelectUser())
                CurrentUserData::getInstace()->setCurrentUserMsg(st_patientMsg);

        }
        else
            QMessageBox::warning(NULL,tr("提示"),tr("未查到该用户信息"));
    }


}

void newUser::slotUpdateUserTable()
{
    updateUserTableWidget();
}

void newUser::changeEvent(QEvent* event)
{
    switch (event->type())
    {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        QWidget::changeEvent(event);
        break;
    }
}

void newUser::showEvent(QShowEvent *event)
{
    Q_UNUSED(event)
    ui->mask_label->setVisible(true);
    ui->save_pushButton->setVisible(false);
}


